package it.tukano.jpgi.test;

import it.tukano.io.FileExt;
import it.tukano.io.Zipper;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author utente4
 */
public class ODSDocument {
    private final FileExt model;
    private final Zipper zipper;
    private static class TableContent extends LinkedList<List<String>> {
        //Default serial version code
        private static final long serialVersionUID = 0;
    };
    private final String cellOpen = "<table:table-cell office:value-type=\"string\">";
    private final String cellClose = "</table:table-cell>";
    private final String tableRowOpen = "<table:table-row table:style-name=\"ro1\">";
    private final String tableRowClose = "</table:table-row>";
    private final String emptyCell = "<table:table-cell/>";
    private final String header;
    private final String footer;
    private final TableContent righe = new TableContent();

    public ODSDocument(String filePath) {
        model = new FileExt(filePath);
        zipper = new Zipper(model);
        final String content = zipper.getEntryAsText("content.xml", "utf-8");
        final int headerIndex = content.indexOf(tableRowOpen);
        final int footerIndex = content.indexOf(tableRowClose) + tableRowClose.length();
        header = content.substring(0, headerIndex);
        footer = content.substring(footerIndex, content.length());
    }
    
    public void addRow(Object... values) {
        LinkedList<String> row = new LinkedList<String>();
        for (Object v : values) {
            String string = v == null ? "" : v.toString();
            row.add("<text:p>" + string + "</text:p>");
        }
        righe.add(row);
    }
    
    public String creaRighe() {
        StringBuilder buffer = new StringBuilder();
        for (List<String> list : righe) {
            buffer.append(tableRowOpen);
            for (String string : list) {
                buffer.append(cellOpen);
                buffer.append(string);
                buffer.append(cellClose);
            }
            buffer.append(tableRowClose);
        }
        return buffer.toString();
    }
    
    public FileExt generateTempDocument(FileExt out) {
        String rows = creaRighe();
        String doc = header + rows + footer;
        try {
            zipper.replace(out.getFile(), "content.xml", doc.getBytes(Charset.forName("utf-8")));
        } catch (IOException ex) {
            Logger.getLogger(ODSDocument.class.getName()).log(Level.SEVERE, null, ex);
        }
        return out;
    }
}
